package org.spiderflow.core.utils;

import org.openqa.selenium.WebDriver;
import org.spiderflow.model.SpiderNode;
import org.spiderflow.selenium.driver.DriverProvider;
import org.spiderflow.selenium.executor.shape.SeleniumExecutor;
import org.spiderflow.selenium.io.SeleniumResponse;

import java.util.Objects;

public class SeleniumHelper {

    /**
     * 通过 selenium 模拟发送请求
     * @param url
     * @return
     */
    public static String open(String url) {
        return open(url, null, null);
    }
    /**
     * 通过 selenium 模拟发送请求
     * @param url
     * @param driverType
     * @return
     */
    public static String open(String url,String driverType) {
        return open(url, driverType, null);
    }

    /**
     * 通过 selenium 模拟发送请求
     *
     * @param url
     * @param driverType
     * @param loadPageWaitTime
     * @return
     */
    public static String open(String url, String driverType, Integer loadPageWaitTime) {
        WebDriver driver = null;
        try {
            SeleniumExecutor seleniumExecutor = SpringContextUtils.getBean(SeleniumExecutor.class);
            DriverProvider driverProvider = seleniumExecutor.getDriverProvider(driverType);
            driver = driverProvider.getWebDriver(new SpiderNode(), null);
            driver.get(url);
            if(Objects.nonNull(loadPageWaitTime)) {
                Thread.sleep(loadPageWaitTime * 1000);
            }
            SeleniumResponse response = new SeleniumResponse(driver);
            return response.getHtml();
        } catch (Exception e) {

        } finally {
            if (driver != null) {
                driver.quit();
            }
        }
        return null;
    }
}
